<template>
  <div class="ui-add-anchor">
    <Modal
      v-model="showModal"
      title="添加搭配图"
      width="634px"
      footer-hide
      :closable ="false"
      :mask-closable="false"
      @on-visible-change="onVisibleChange"
    >
      <div class="ice-anchor-manager-new">
        <div class="ice-anchor-manager-cover">
          <div
            :class="
              `ice-anchor-img-container ${addAnchorImg.containerClassName}`
            "
            :data-i="addAnchorImg.i"
            :data-key="addAnchorImg.key"
            @click="onAddAnchorDot"
          >
            <img
              :src="
                `${addAnchorImg.url}?x-oss-process=image/crop,x_${addAnchorImg.x},y_${addAnchorImg.y},w_${addAnchorImg.w},h_${addAnchorImg.h}`
              "
            />
            <div class="ice-anchor" v-if="anchor">
              <ui-anchor
                :x="anchor.x"
                :y="anchor.y"
                @dropped="onAddAnchorDropped"
              >
                <div class="ice-anchor-point-placeholder">+</div>
              </ui-anchor>
            </div>
            <div
              :class="`ice-anchor-item ice-anchor-item-${item.pos}`"
              v-for="(item, i) in addAnchorImg.anchorList"
              :key="i"
              :style="item[item.pos]"
              @click.stop="() => {}"
            >
              <div
                class="ice-anchor-item-dot"
                :data-i="i"
                :data-imgi="addAnchorImg.i"
                @click.stop="changePos"
              ></div>
              <div class="ice-anchor-item-arrow"></div>
              <div
                class="ice-anchor-item-title"
                :data-i="i"
                :data-imgi="addAnchorImg.i"
                @click.stop="onEditAnchorTag"
              >
                {{ item.anchorType === 'goods' ? item.anchorGoodsTag : item.anchorTag }}
              </div>
            </div>
          </div>
        </div>
        <div class="ice-anchor-manager-points">
          <div
            class="ice-anchor-manager-points-help"
            v-if="!anchor && !anchorEdit"
          >
            <p>
              请在左侧选择合适的位置点击添加
              <span style="color: red;">0~5</span>个标签。
            </p>
            <p>1.点击红点可以切换标签方向，</p>
            <p>2.适当添加和图片相关联的标签有助于提升内容品质哦</p>
          </div>
          <div class="ice-anchor-editor" v-else>
            <Form
              ref="anchorForm"
              :model="anchorForm"
              :rules="anchorRules"
              label-position="top"
            >
              <Tabs
                type="card"
                :animated="false"
                :value="anchorType"
                @on-click="onAnchorTypeChange"
              >
                <TabPane label="添加宝贝" name="goods">
                  <FormItem
                    label="商品标签"
                    prop="anchorGoodsTag"
                    v-if="anchorType === 'goods'"
                  >
                    <Input
                      type="text"
                      v-model="anchorForm.anchorGoodsTag"
                      maxlength="10"
                      show-word-limit
                      placeholder="请输入不超过10个汉字"
                    />
                  </FormItem>

                  <FormItem
                    label="添加宝贝"
                    v-if="anchorType === 'goods'"
                  >
                    <div class="pls-face-item" v-if="anchorForm.anchorGoodsCover">
                      <img :src="anchorForm.anchorGoodsCover" />
                      <div class="pls-face-operation">
                        <div @click="onAddItem">
                          <Icon type="ios-cloud-upload-outline" />
                        </div>
                        <div @click="onRmFaceItem">
                          <Icon type="ios-trash-outline" />
                        </div>
                      </div>
                    </div>
                    <div class="pls-add-image-new size-134" style="width:90px;height:90px;" v-else  @click="onAddItem">
                      <Icon type="ios-add" size="56" color="#6af" style="margin-top:24px;margin-bottom:-5px;" />
                      <span>添加宝贝</span>
                    </div>
                  </FormItem>

                </TabPane>
                <TabPane label="添加文本标签" name="textTag">
                  <FormItem
                    label="文本标签"
                    prop="anchorTag"
                    v-if="anchorType === 'textTag'"
                  >
                    <Input
                      type="text"
                      v-model="anchorForm.anchorTag"
                      maxlength="10"
                      show-word-limit
                      placeholder="请输入不超过10个汉字"
                    />
                  </FormItem>
                </TabPane>
              </Tabs>
              <FormItem>
                <Button type="primary" @click="handleAnchorSubmit">{{
                  anchorEdit ? '修改' : '添加'
                }}</Button>
                <Button
                  type="error"
                  ghost
                  style="margin-left: 8px"
                  @click="onDelAnchor"
                  >删除此条</Button
                >
              </FormItem>
            </Form>
          </div>
        </div>
      </div>
      <div class="iai-add-image__selectbar_new" v-if="mode === 'add'">
        <div class="iai-add-image__list">
          <div
            class="iai-add-image__selectbar-item"
            v-for="img in anchorImages"
            :key="img.key"
            :data-key="img.key"
            :class="addAnchorImg.key === img.key ? 'selected' : ''"
            @click="onChangeAnchorImg"
          >
            <div class="iai-add-image__selectbar-item-cover">
              <img
                :src="
                  `${img.url}?x-oss-process=image/crop,x_${img.x},y_${img.y},w_${img.w},h_${img.h}`
                "
              />
            </div>
          </div>
        </div>
      </div>
      <div class="ice-add-image-dialog-new__footer">
        <div class="ice-add-image-dialog-new__footer__limit"></div>
        <div class="ice-add-image-dialog-new__footer__operation">
          <Button type="primary" @click="onSubmit" :disabled="!canSubmit"
            >确定</Button
          >
          <Button @click="onHide">取消</Button>
        </div>
      </div>
    </Modal>

  <ui-add-item
    ref="uiAddItem"
    :itemData="anchorForm.goods"
    @on-export="onExportGood"
  />

</div>
</template>

<script>
import UiAnchor from './UiAnchor.vue'
import UiAddItem from '@/components/ui/UiAddItem.vue'

const anchorSize = 22
const anchorSizeHalf = anchorSize / 2
export default {
  name: 'ui-add-anchor',
  components: {
    UiAnchor,
    UiAddItem,
  },
  props: {
    show: Boolean,
    images: {
      type: Array,
      default() {
        return []
      }
    },
    imagesIndex: {
      type: Number,
      default: 0
    },
    mode: {
      type: String,
      default: 'add'
    }
  },
  watch: {
    show(newVal, oldVal) {
      console.log(newVal, oldVal)
      if (newVal !== oldVal) {
        this.showModal = newVal
      }
    },
    images(newVal) {
      this.anchorImages = newVal.map(item => item)
    }
  },
  data() {
    return {
      showModal: false,
      addAnchorImg: {
        url: '',
        key: '',
        i: ''
      },
      anchorImages: [],
      anchor: null,
      anchorForm: {
        anchorTag: '',
        anchorGoodsCover: '',
        anchorGoodsTag: '',
        goods: {},
      },
      anchorRules: {
        anchorTag: [
          {
            required: true,
            message: '文本标签不能为空',
            trigger: 'blur'
          }
        ],
        anchorGoodsTag: [
          {
            required: true,
            message: '商品标签不能为空',
            trigger: 'blur'
          }
        ],
      },
      anchorType: 'goods',
      anchorForImg: '',
      anchorEdit: false,
      anchorIndex: -1,
      canSubmit: true,

    }
  },
  methods: {
    onVisibleChange(res) {
      if (res) {
        this.addAnchorImg = {
          ...this.images[this.imagesIndex]
        }
      } else {
        this.addAnchorImg = {}
        this.addAnchorImg = []
        this.onResetAnchorForm()
      }
    },
    onChangeAnchorImg(e) {
      const { key } = e.currentTarget.dataset

      this.addAnchorImg = {
        ...this.anchorImages.filter(item => item.key === key)[0]
      }
      this.onResetAnchorForm()
    },
    onAddAnchorDot(e) {
      const { i } = e.currentTarget.dataset
      const addIndex = this.mode === 'add' ? i : 0
      const anchors = this.anchorImages[addIndex].anchorList.length

      if (this.anchor || this.anchorEdit || anchors === 5) return

      this.canSubmit = false
      const { offsetX, offsetY, target } = e
      const { clientWidth, clientHeight } = target
      const x = offsetX - anchorSizeHalf > 0 ? (offsetX - anchorSizeHalf) : 0     // lan add for avoid negative
      const y = offsetY - anchorSizeHalf > 0 ? (offsetY - anchorSizeHalf) : 0
      const anchor = {
        x,
        y,
        xPer: (x / clientWidth) * 100,
        yPer: (y / clientHeight) * 100
      }
      this.$set(this.anchorImages, addIndex, {
        ...this.anchorImages[addIndex],
        anchor
      })
      this.anchor = anchor
      this.anchorIndex = -1
      this.$set(this.addAnchorImg, 'anchor', anchor)
    },
    onAddAnchorDropped({ left, top, parent: { width, height } }) {
      const i = this.mode === 'add' ? this.addAnchorImg.i : 0
      const anchor = {
        x: left,
        y: top,
        xPer: (left / width) * 100,
        yPer: (top / height) * 100
      }
      this.$set(this.anchorImages, i, {
        ...this.anchorImages[i],
        anchor
      })
      this.$set(this.addAnchorImg, 'anchor', anchor)
    },
    onAnchorTypeChange(e) {
      this.anchorType = e
    },
    changePos(e) {
      const { i, imgi } = e.currentTarget.dataset
      this.$set(this.addAnchorImg, 'anchorList', this.addAnchorImg.anchorList.map((item, idx) => {
        if (Number(i) === idx) {
          return {
            ...item,
            pos: item.pos === 'right' ? 'left' : 'right'
          }
        }
        return item
      }))
      this.$nextTick(() => {
        this.$set(this.anchorImages, this.mode === 'add' ? imgi : 0, {
          ...this.addAnchorImg
        })
      })
    },
    handleAnchorSubmit() {
      const i = this.mode === 'add' ? this.addAnchorImg.i : 0
      this.$refs['anchorForm'].validate(valid => {
        if (valid) {
          if(this.anchorForm.anchorGoodsTag !== '')
            if(this.anchorForm.anchorGoodsCover === '') {
              this.$Message.warning({
                  content: '宝贝不能为空',
                  duration: 6
              });
              return
            }
          let anchorList = []
          if (this.anchorEdit) {
            anchorList = this.anchorImages[i].anchorList.map((item, index) => {
              if (this.anchorIndex === index) {
                return {
                  ...item,
                  anchorType: this.anchorType,
                  ...this.anchorForm
                }
              }
              return item
            })
          } else {
            const { xPer, yPer } = this.addAnchorImg.anchor
            anchorList = [
              ...this.anchorImages[i].anchorList,
              {
                ...this.addAnchorImg.anchor,
                anchorType: this.anchorType,
                ...this.anchorForm,
                pos: xPer > 50 ? 'right' : 'left',
                left: {
                  top: `${yPer}%`,
                  left: `${xPer}%`,
                  maxWidth: `${100 - xPer}%`
                },
                right: {
                  top: `${yPer}%`,
                  right: `calc(${100 - xPer}% - ${anchorSizeHalf}px)`,
                  maxWidth: `${xPer}%`
                }
              }
            ]
          }
          this.$set(this.anchorImages, i, {
            ...this.anchorImages[i],
            anchorList,
            anchor: null
          })
          this.$set(this.addAnchorImg, 'anchorList', anchorList)
          this.$set(this.addAnchorImg, 'anchor', null)
          // this.$set(this.anchorForm, 'anchorTag', '')
          // this.$refs['anchorForm'].resetFields()
          this.onResetAnchorForm()
        }
      })
    },
    onEditAnchorTag(e) {
      // console.warn('eeeeeeeeeeeeeeeeeeee', e)
      const { i, imgi } = e.currentTarget.dataset
      const currentImg = this.anchorImages[this.mode === 'add' ? imgi : 0]
      const { anchorList } = currentImg
      const { anchorTag, anchorGoodsTag, anchorGoodsCover, anchorType, goods } = anchorList[i]
      this.anchorType = anchorType
      this.anchorForm = {
        anchorTag,
        anchorGoodsCover,
        anchorGoodsTag,
        goods
      }
      // this.$set(this.anchorForm, 'anchorTag', anchorList[i].anchorTag)
      this.anchorEdit = true
      this.anchorIndex = Number(i)
      this.canSubmit = false
    },
    onDelAnchor() {
      const i = this.mode === 'add' ? this.addAnchorImg.i : 0
      if (this.anchorIndex > -1) {
        const anchorList = this.addAnchorImg.anchorList.filter(
          (item, index) => index !== this.anchorIndex
        )
        this.$set(this.anchorImages, i, {
          ...this.anchorImages[i],
          anchorList
        })
        this.$set(this.addAnchorImg, 'anchorList', anchorList)
      }
      this.onResetAnchorForm()
    },
    onResetAnchorForm() {
      this.anchorForm = {
        anchorTag: '',
        anchorGoodsCover: '',
        anchorGoodsTag: '',
        goods: {}
      }
      this.anchorEdit = false
      this.anchorType = 'goods'
      this.anchorIndex = -1
      this.anchor = null
      this.canSubmit = true
    },
    onSubmit() {
      this.$emit('on-change', {
        images: this.anchorImages
      })
      this.onHide()
    },
    onHide() {
      this.$emit('on-visible-change', false)
    },

    // 添加宝贝相关一些操作方法
    onAddItem() {
      this.$refs['uiAddItem'].init()
    },
    onRmFaceItem() {
      this.anchorForm.goods = {}
      this.anchorForm.anchorGoodsCover = ''
      this.$refs['uiAddItem'].delete()
    },
    onExportGood(res) {
      const { item } = res
      const data = item

      this.anchorForm.goods = data
      this.anchorForm.anchorGoodsCover = data.pic_url
      this.showAddGoodModal = false
    },

  },
  mounted() {}
}
</script>

<style lang="scss" scoped>
.ice-anchor-manager-new {
  width: 100%;
  display: flex;
  background-color: #f4f4f4;
}
.ice-anchor-manager-cover {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 0 0 300px;
  height: 300px;
}
.ice-anchor-img-container {
  position: relative;
  &.container-1-1 {
    width: 300px;
    height: 300px;
  }
  &.container-3-4 {
    width: 225px;
    height: 300px;
  }
  &.container-4-3 {
    width: 300px;
    height: 225px;
  }
  > img {
    width: 100%;
    height: 100%;
  }
}

.ice-anchor {
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  position: absolute;
}

.cropper-anchor-view {
  display: flex;
  flex-wrap: wrap;
}
.cropper-anchor-view--item {
  width: 200px;
  height: 200px;
  margin-right: 16px;
  img {
    max-width: 100%;
    max-height: 100%;
  }
}

.ice-anchor-point-placeholder {
  background-color: rgba(0, 0, 0, 0.5);
  height: 22px;
  width: 22px;
  color: #fff;
  font-size: 12px;
  line-height: 22px;
  text-align: center;
  border-radius: 50%;
}

.ice-anchor-manager-points {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.ice-anchor-manager-points-help {
  width: 240px;
  color: #999;
  font-size: 16px;
  line-height: 24px;
  p {
    margin-bottom: 7px;
    font-size: 14px;
    font-weight: 400;
    line-height: 20px;
  }
}

.ice-anchor-editor {
  width: 100%;
  align-self: flex-start;
  padding: 10px;
}

.pls-face-item {
  width: 90px;
  height: 90px;
  position: relative;
  margin-bottom: 10px;
  img {
    width: 100%;
    max-width: 100%;
    max-height: 100%;
  }
  &:hover {
    .pls-face-operation {
      display: flex;
    }
  }
}
.pls-face-operation {
  width: 100%;
  height: 24px;
  position: absolute;
  left: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 1;
  display: none;
  > div {
    height: 100%;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    color: #fff;
    cursor: pointer;
    & + div {
      border-left: #fff solid 1px;
    }
  }
}
</style>
